<?php

namespace App\Http\Controllers\Wx;

use App\CodeResponse;
use App\Models\User;
use App\Services\UserServices;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;

class AuthController extends WxController
{
    protected $only = ['info'];

    /**
     * 用户注册
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \App\Exceptions\BusinessException
     */
    public function register(Request $request)
    {
        // 获取参数
        $username = $request->input('username');
        $password = $request->input('password');
        $mobile = $request->input('mobile');
        $code = $request->input('code');

        // 验证参数是否为空
        if (empty($username) || empty($password) || empty($mobile) || empty($code)) {
            return $this->fail(CodeResponse::PARAM_ILLEGAL);
        }

        // 验证用户是否存在
        $user = (new UserServices())->getByUsernane($username);
        if (!is_null($user)) {
            return $this->fail(CodeResponse::AUTH_NAME_REGISTERED);
        }

        $validator = Validator::make(['mobile' => $mobile], ['mobile' => 'regex:/^1[0-9]{10}$/']);
        if ($validator->fails()) {
            return $this->fail(CodeResponse::AUTH_INVALID_MOBILE);
        }
        // 验证手机号是否存在
        $user = (new UserServices())->getByMobile($mobile);
        if (!is_null($user)) {
            return $this->fail(CodeResponse::AUTH_MOBILE_REGISTERED);
        }
        //验证验证码是否正确
        (new UserServices())->checkCaptcha($mobile, $code);

        //写入用户表
        $user = new User();
        $user->username = $username;
        $user->password = Hash::make($password);
        $user->mobile = $mobile;
        $user->avatar = '';
        $user->nickname = $username;
        $user->last_login = Carbon::now()->toDateString();//'Y-m-d H-i-s'
        $user->last_ligin_ip = $request->getClientIp();
        $user->save();

        // 新用户发券

        // 返回token
        return $this->success([
            'token' => '',
            'userInfo' => [
                'nickName' => $username,
                'avatarUrl' => $user->avatar
            ]
        ]);
    }

    public function regCaptcha(Request $request)
    {
        //获取手机号
        $mobile = $request->input('mobile');
        //验证手机号是否合法
        if (empty($mobile)) {
            return $this->fail(CodeResponse::PARAM_ILLEGAL);
        }
        $validator = Validator::make(['mobile' => $mobile], ['mobile' => 'regex:/^1[0-9]{10}$/']);
        if ($validator->fails()) {
            return $this->fail(CodeResponse::AUTH_INVALID_MOBILE);
        }
        //验证手机号是否已被注册
        $user = (new UserServices())->getByMobile($mobile);
        if (!is_null($user)) {
            return $this->fail(CodeResponse::AUTH_MOBILE_REGISTERED);
        }
        //防刷验证，一分钟内只能请求一次，当天只能请求10次
        $lock = Cache::add('register_captcha_lock_' . $mobile, 1, 60);
        if (!$lock) {
            return $this->fail(CodeResponse::AUTH_CAPTCHA_FREQUENCY);
        }
        $isPass = (new UserServices())->checkMobileSendCaptchaCount($mobile);
        if (!$isPass) {
            return $this->fail(CodeResponse::AUTH_CAPTCHA_FREQUENCY, '验证码当天只能请求10次');
        }
        $code = (new UserServices())->setCaptcha($mobile);
        //发送信息 easy-sms
        (new UserServices())->sendCaptchaMsg($mobile, $code);
        return ['errno' => 0, 'errmsg' => '成功', 'data' => null];
    }

    /**
     * 账号登录
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function login(Request $request)
    {
        // 获取参数
        $username = $request->input('username');
        $password = $request->input('password');
        // 验证参数是否为空
        if (empty($username) || empty($password)) {
            return $this->fail(CodeResponse::PARAM_ILLEGAL);
        }
        $user = UserServices::getInstance()->getByUsername($username);
        if (!is_null($user)) {
            return $this->fail(CodeResponse::AUTH_INVALID_ACCOUNT);
        }
        $isPass = Hash::check($password, $user->getAuthPassword());
        if (!$isPass) {
            return $this->fail(CodeResponse::AUTH_INVALID_ACCOUNT, '账户密码不正确');
        }
        $user->last_login_time = now()->toDateTimeString();
        $user->last_login_ip = $request->getClientIp();
        if (!$user->save()) {
            return $this->fail(CodeResponse::UPDATED_FAIL);
        };
        //获取token,jwt生成
        $token = Auth::guard('wx')->login($user);
        //组装数据并返回
        return $this->success([
            'token' => $token,
            'userInfo' => [
                'nickName' => $username,
                'avatarUrl' => $user->avatar
            ]
        ]);
    }

    /**
     * 获取用户信息
     * @return \Illuminate\Http\JsonResponse
     */
    public function info(){
        $user = $this->user();
        return $this->success([
            'nickName'=>$user->nickName,
            'avatar'=>$user->avatar,
            'gender'=>$user->gender,
            'mobile'=>$user->mobile,
        ]);
    }

    /**
     * 账号登出
     * @return \Illuminate\Http\JsonResponse
     */
    public function logout(){
        Auth::guard('wx')->logout();
        return $this->success();
    }

    /**
     * 重置密码
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function reset(Request $request){
        $password = $request->input('password');
        $mobile = $request->input('mobile');
        $code = $request->input('code');
        if(empty($password)||empty($mobile)||empty($code)){
            return $this->fail(CodeResponse::PARAM_ILLEGAL);
        }
        $isPass = UserServices::getInstance()->checkCaptcha($mobile,$code);
        if(!$isPass){
            return $this->fail(CodeResponse::AUTH_CAPTCHA_UNMATCH);
        }
        $user = UserServices::getInstance()->getByMobile($mobile);
        if(!$user){
            return $this->fail(CodeResponse::AUTH_MOBILE_UNREGISTERED);
        }
        $user->password = Hash::make($password);
        $ret = $user->save();
        return $this->failOrSuccess($ret,CodeResponse::UPDATED_FAIL);
    }

    public function profile(Request $request){
        $user = $this->user();
        $avatar=$request->input('avatar');
        $gender=$request->input('gender');
        $nickame=$request->input('nickname');

        if(!empty($avatar)){
            $user->avatar = $avatar;
        }
        if(!empty($gender)){
            $user->gender = $gender;
        }
        if(!empty($nickame)){
            $user->nickame = $nickame;
        }
        $ret = $user->save();
        return $this->failOrSuccess($ret,CodeResponse::UPDATED_FAIL);
    }
}
